﻿using System.IO;
using System.Web;
using System.Web.Configuration;
using System.Text;

namespace AjaxUploadServer
{
	public abstract class ServerContext
	{
		public ServerContext(string filename, HttpContextBase context)
		{
			if (string.IsNullOrEmpty(filename))
			{
				throw new System.ArgumentNullException("key");
			}
			_filename = GetServerFileName(filename, context);
		}
		public ServerContext(string filename, IServerManager server)
		{
			if (string.IsNullOrEmpty(filename))
			{
				throw new System.ArgumentNullException("key");
			}
			_filename = GetServerFileName(filename, server);
		}
		protected readonly string _filename;

		public virtual string LoadJson()
		{
			var json = File.ReadAllText(_filename, Encoding.UTF8);
			return json;
		}

		/// <summary>
		/// 读取配置
		/// </summary>
		public abstract void Load();

		/// <summary>
		/// 从web.config.appSetting中读取value
		/// </summary>
		/// <param name="key">appSetting项键</param>
		/// <param name="defaultValue">当appSetting未配置此项时的默认值</param>
		/// <returns>值</returns>
		public static string GetValueFromConfigure(string key, string defaultValue)
		{
			return WebConfigurationManager.AppSettings[key] ?? defaultValue;
		}
		/// <summary>
		/// 获取文件物理位置
		/// </summary>
		/// <param name="name">文件名</param>
		/// <param name="context">当前请求上下文</param>
		/// <returns>文件物理路径</returns>
		public static string GetServerFileName(string name, HttpContextBase context)
		{
			return context.Server.MapPath(name ?? string.Empty);
		}
		/// <summary>
		/// 获取文件物理位置
		/// </summary>
		/// <param name="name">文件名</param>
		/// <param name="server">IServerManager</param>
		/// <returns>文件物理路径</returns>
		public static string GetServerFileName(string name, IServerManager server)
		{
			return server.MapPath(name ?? string.Empty);
		}
		/// <summary>
		/// 创建一个ServerContext对象
		/// </summary>
		/// <typeparam name="TT">类型</typeparam>
		/// <param name="args">构造函数参数</param>
		/// <returns>新的ServerContext对象</returns>
		public static TT Create<TT>(params object[] args) where TT : ServerContext
		{
			var t = System.Activator.CreateInstance(typeof(TT), args);
			return (TT)t;
		}
	}
	public abstract class ServerContext<T> : ServerContext where T : ServerContext
	{
		public ServerContext(string filename, HttpContextBase context) : base(filename, context) { }
		public static T Create(string filename, HttpContextBase context)
		{
			return Create<T>(filename, context);
		}
		public static T CreateFromConfigure(string key, HttpContextBase context)
		{
			return Create<T>(GetValueFromConfigure(key, null), context);
		}

		public ServerContext(string filename, IServerManager server) : base(filename, server) { }
		public static T Create(string filename, IServerManager server)
		{
			return Create<T>(filename, server);
		}
		public static T CreateFromConfigure(string key, IServerManager server)
		{
			return Create<T>(GetValueFromConfigure(key, null), server);
		}
	}
}